﻿Imports ISNet.WebUI.WebGrid
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports log4net


Partial Class mtCommitItems
    Inherits System.Web.UI.Page

    Private Shared logger As ILog = LogManager.GetLogger("mtCommitItems")

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        ScreenName.Text = "ระบบจัดทำงบประมาณ  >>  ตั้งค่าระบบ >>  Commitment Item"
        'Session("users") = "bb0011"
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If
        
        If IsPostBack = False Then
            PlanYearsTxt.Text = Session("PlanYear")
            Session("PlanYearTxt") = PlanYearsTxt.Text
            Session("SearchTxt") = ""
            Session("SearchTxt") = " and Cmmts.PlanYear = " & PlanYearsTxt.Text
        Else
            ' PlanYearsTxt.Text = Session("PlanYearTxt")
        End If
    End Sub

    Protected Sub WebGrid1_InitializeDataSource(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.DataSourceEventArgs) Handles WebGrid1.InitializeDataSource
        Dim adapter As New MasterDataSet2TableAdapters.CmmtsTableAdapter
        Dim dtTable As New MasterDataSet2.CmmtsDataTable

        Dim sql As String = "select *, "
        sql += " CASE "
        sql += " WHEN TemplateName IS NULL THEN 0 "
        sql += " WHEN TemplateName = '' THEN 0 "
        sql += " ELSE 1 "
        sql += " END Attachments_amount "
        'sql += " ,BudgetDetails.Id AS BudgetDetails_id "
        sql += " from Cmmts "
        'sql += " LEFT JOIN BudgetDetails ON Cmmts.CmmtCode = BudgetDetails.Cmmt_CmmtCode "
        'sql += " and Cmmts.PlanYear = BudgetDetails.Cmmt_PlanYear "
        sql += " WHERE 1 = 1 "

        sql += Session("SearchTxt")
        sql += " ORDER BY CmmtCode "

        adapter.SearchCmmts(dtTable, sql)

        Session("count_data") = dtTable.Rows.Count

        dtTable.Columns("PlanYear").AllowDBNull = True
        dtTable.Columns("CmmtCode").AllowDBNull = True
        dtTable.Columns("id").AllowDBNull = True
        dtTable.Columns("id").ReadOnly = False

        e.DataSource = dtTable

    End Sub

    Protected Sub WebGrid1_InitializeRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        ' don't edit column
        e.Row.Cells(2).ForceNoEdit = True
        e.Row.Cells(5).ForceNoEdit = True
        e.Row.Cells(6).ForceNoEdit = True
        e.Row.Cells(7).ForceNoEdit = True
    End Sub

    Protected Sub WebGrid1_InitializePostBack(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.PostbackEventArgs)
        If e.Action = PostBackAction.Custom Then
            Dim type As String = TryCast(Request("type"), String)
            Dim Deletet As String = TryCast(Request("id"), String)
            Dim code As String = TryCast(Request("code"), String)
            Dim yr As String = TryCast(Request("year"), String)
            'Dim id = Deletet.Split(",")
            'Dim idd = id(0)
            'Dim idy = id(1)
            Dim adapter As New MasterDataSet2TableAdapters.CmmtsTableAdapter
            Dim adap2 As New MasterDataSet2TableAdapters.checkuseTableAdapter
            ' MsgBox(Deletet)
            Try
                Dim used As Integer = adap2.CheckCmmt(code, Val(yr))
                If Type = "1" Then
                    If used = 0 Then
                        Dim adapter2 As New MasterDataSet2TableAdapters.CmmtFundCentersTableAdapter
                        adapter2.DeleteFromCmmt(Deletet)
                        adapter.DeleteQuery(Deletet)

                        logger.Info("User " & Session("users") & " delete commitment item " & Deletet)
                    Else
                        WebGrid1.ClientAction.Alert("ไม่สามารลบข้อมูลได้เนื่องจากข้อมูลถูกนำไปใช้งานแล้ว")
                    End If

                ElseIf Type = "2" Then
                    If used = 0 Then
                        For Each keyValue As String In WebGrid1.RootTable.GetCheckedRows()
                            Dim adapter2 As New MasterDataSet2TableAdapters.CmmtFundCentersTableAdapter
                            adapter2.DeleteFromCmmt(keyValue)
                            adapter.DeleteQuery(keyValue)
                            logger.Info("User " & Session("users") & " delete commitment item " & Deletet)
                        Next keyValue
                    Else
                        WebGrid1.ClientAction.Alert("ไม่สามารลบข้อมูลบางรายการได้เนื่องจากข้อมูลถูกนำไปใช้งานแล้ว")
                    End If

                End If

            Catch ex As Exception
                logger.Error(ex.Message)
                logger.Error(ex.StackTrace)
                WebGrid1.ClientAction.Alert("ไม่สามารลบข้อมูลได้กรุณาติดต่อผู้ดูแลระบบ")
            End Try

            WebGrid1.ClientAction.Refresh()
        End If
    End Sub

    Protected Sub WebGrid1_AddRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        Dim adapter As New MasterDataSet2TableAdapters.CmmtsTableAdapter

        Dim count = adapter.CheckDup(e.Row.Cells(1).Value, e.Row.Cells(2).Value, e.Row.Cells(3).Value)
        If count <> 0 Then
            WebGrid1.ClearCachedDataSource()
            WebGrid1.ClientAction.Refresh()
            Throw New ArgumentException("ข้อมูล Commitment Item ซ้ำกับที่มีอยู่ กรุณาตรวจสอบ")
        Else
            Dim id As Decimal
            id = adapter.InsertQuery(e.Row.Cells(1).Value, e.Row.Cells(2).Value, e.Row.Cells(3).Value, If(e.Row.Cells(4).Value = "" Or Nothing, "", e.Row.Cells(4).Value), Date.Now, Session("users"))
            Dim dr As DataRow = e.Row.DataRow
            dr("id") = id

            logger.Info("User " & Session("users") & " insert commitment item " & e.Row.Cells(1).Value)
            WebGrid1.ClientAction.Refresh()
        End If
    End Sub

    Protected Sub WebGrid1_UpdateRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        Dim id As String
        id = e.Row.KeyValue
        Dim count = 0
        Dim adapter As New MasterDataSet2TableAdapters.CmmtsTableAdapter
        If e.Row.Cells(3).Text = "" Then
            count = adapter.CheckDupUpdate(e.Row.Cells(1).Value, e.Row.Cells(2).Value, Nothing, id)
        Else
            count = adapter.CheckDupUpdate(e.Row.Cells(1).Value, e.Row.Cells(2).Value, If(IsDBNull(e.Row.Cells(4).Value), "", If(e.Row.Cells(4).Value = "" Or Nothing, "", e.Row.Cells(4).Value)), id)
        End If

        If count > 1 Then
            WebGrid1.ClearCachedDataSource()
            WebGrid1.ClientAction.Refresh()
            Throw New ArgumentException("ข้อมูล Commitment Item ซ้ำกับที่มีอยู่ กรุณาตรวจสอบ")
        Else
            Dim adap2 As New MasterDataSet2TableAdapters.checkuseTableAdapter
            Dim dt As MasterDataSet2.CmmtsDataTable
            dt = adapter.GetDataById(Val(id))
            Dim oldcode As String = dt.Item(0).CmmtCode
            Dim oldyear As Integer = dt.Item(0).PlanYear
            Dim used As Integer = adap2.CheckCmmt(oldcode, oldyear)
            If oldcode.Trim = e.Row.Cells(1).Value.ToString.Trim And oldyear = Val(e.Row.Cells(2).Value) Then
                used = 0
            End If

            If used = 0 Then
                If e.Row.Cells(3).Text = "" Then
                    adapter.UpdateQuery(e.Row.Cells(1).Value, e.Row.Cells(2).Value, e.Row.Cells(3).Value, Nothing, Date.Now, Session("users"), id)
                Else
                    adapter.UpdateQuery(e.Row.Cells(1).Value, e.Row.Cells(2).Value, e.Row.Cells(3).Value, If(IsDBNull(e.Row.Cells(4).Value), "", If(e.Row.Cells(4).Value = "" Or Nothing, "", e.Row.Cells(4).Value)), Date.Now, Session("users"), id)
                End If

                logger.Info("User " & Session("users") & " insert commitment item " & e.Row.Cells(1).Value)
            Else
                WebGrid1.ClientAction.Refresh()
                WebGrid1.ClientAction.Alert("ไม่สามารแก้ไขข้อมูลได้เนื่องจากข้อมูลถูกนำไปใช้งานแล้ว")
            End If
        End If
    End Sub

    Protected Sub SearhBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SearhBtn.Click
        Session("SearchTxt") = ""
        Session("SearchTxt") += " and Cmmts.PlanYear = " & Val(PlanYearsTxt.Text)

        If SearchCode.Text <> "" Then
            Session("SearchTxt") += " and CmmtCode like '%" & SearchCode.Text & "%'"
        End If

        If SearchTxt.Text <> "" Then
            Session("SearchTxt") += " and Description like '%" & SearchTxt.Text & "%'"
        End If
        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()
        t_countdata.Visible = True
        If Val(Session("count_data")) > 0 Then
            L_CountData.Text = FormatNumber(Val(Session("count_data")), 0) & " รายการ"
        Else
            L_CountData.Text = "ไม่พบข้อมูลที่ค้นหา"
        End If
    End Sub

    Protected Sub SaveBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SaveBtn.Click
        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()
    End Sub

End Class
